﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net.Sockets;
using System.Reactive;
using System.Text;
using System.Threading.Tasks;
using Aspose.Cells;
using FastReport;
using FastReport.Export.Pdf;
using Mapster;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using Senparc.Weixin.Work.AdvancedAPIs.OaDataOpen;
using SHZY.BaseData.Entitys.Common.Entity;
using SHZY.BaseData.Entitys.Dto.QmsBaseCustomer;
using SHZY.BaseData.Entitys.Entity;
using SHZY.Business.Entity.Common;
using SHZY.Business.Entitys.Common.Dto.PrintExecute;
using SHZY.Business.Entitys.Common.Entity;
using SHZY.Business.Entitys.Dto.pick;
using SHZY.Business.Entitys.Dto.pickrecord;
using SHZY.Business.Entitys.Entity;
using SHZY.Business.Entitys.Entity.VideoRecording;
using SHZY.Business.Interfaces;
using SHZY.ClayObject;
using SHZY.Common.Configuration;
using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Manager.Files;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Extension;
using SHZY.Common.Filter;
using SHZY.Common.FR;
using SHZY.Common.Models.NPOI;
using SHZY.Common.Security;
using SHZY.DataEncryption;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Interfaces.System;
using SqlSugar;
using static SHZY.Common.Security.NetHelper;

namespace SHZY.Business
{
    /// <summary>
    /// 业务实现：装箱单.
    /// </summary>
    [ApiDescriptionSettings(Tag = "Business", Name = "QmsBusiPick", Order = 200)]
    [Route("api/Business/[controller]")]
    public class QmsBusiPickService : IQmsBusiPickService, IDynamicApiController, ITransient
    {
        /// <summary>
        /// 服务基础仓储.
        /// </summary>
        private readonly ISqlSugarRepository<QmsBusiPickEntity> _repository;

        /// <summary>
        /// 多租户事务.
        /// </summary>
        private readonly ITenant _db;

        private readonly ISqlSugarClient _client;
        /// <summary>
        /// 数据接口服务.
        /// </summary>
        private readonly IDataInterfaceService _dataInterfaceService;

        /// <summary>
        /// 用户管理.
        /// </summary>
        private readonly IUserManager _userManager;

        /// <summary>
        /// 文件服务.
        /// </summary>
        private readonly IFileManager _fileManager;

        /// <summary>
        /// 初始化一个<see cref="QmsBusiPickService"/>类型的新实例.
        /// </summary>
        public QmsBusiPickService(
            ISqlSugarRepository<QmsBusiPickEntity> qmsBusiPickRepository,
            IDataInterfaceService dataInterfaceService,
            ISqlSugarClient context,
            IUserManager userManager, IFileManager fileManager)
        {
            _repository = qmsBusiPickRepository;
            _dataInterfaceService = dataInterfaceService;
            _db = context.AsTenant();
            _client = context;
            _userManager = userManager;
            _fileManager = fileManager;
        }

        /// <summary>
        /// 打印条码查看.
        /// </summary>
        /// <param name="id">主键值.</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var data = _repository.Context.Queryable<QmsBusiPickEntity, QmsBusiPickRecordEntity>((a, b) => new JoinQueryInfos(JoinType.Left, a.Id == b.PickId))
                .Where((a, b) => a.Id == id)
                .Where((a, b) => a.DeleteMark == null && b.DeleteMark == null)
                .Select((a, b) => new QmsBusiPickRecordListOutput()
                {
                    id = b.Id,
                    no = b.No,
                    name = b.Name,
                    model = b.Model,
                    boxNo = b.BoxNo,
                    boxName = b.BoxName,
                    drawingNo = b.DrawingNo,
                    componentName = b.ComponentName,
                    specifications = b.Specifications,
                    unit = b.Unit,
                    qty = b.Qty,
                    remark = b.Remark,
                    barcode = b.Barcode,
                    printDate = b.PrintDate,
                }).ToList();
            return data;
        }

        /// <summary>
        /// 获取装箱单列表.
        /// </summary>
        /// <param name="input">请求参数.</param>
        /// <returns></returns>
        [HttpGet("GetList")]
        public async Task<dynamic> GetList([FromQuery] QmsBusiPickListQueryInput input)
        {
            var data = await _repository.Context.Queryable<QmsBusiPickEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.no), it => it.No.Contains(input.no))
                .WhereIF(!string.IsNullOrEmpty(input.model), it => it.Model.Contains(input.model))
                .WhereIF(!string.IsNullOrEmpty(input.printStatus), it => it.PrintStatus.ToString().Contains(input.printStatus))
                .WhereIF(!string.IsNullOrEmpty(input.boxNo), it => it.BoxNo.Contains(input.boxNo))
                .WhereIF(!string.IsNullOrEmpty(input.drawingNo), it => it.DrawingNo.Contains(input.drawingNo))
                .WhereIF(!string.IsNullOrEmpty(input.componentName), it => it.ComponentName.Contains(input.componentName))
                .WhereIF(!string.IsNullOrEmpty(input.specifications), it => it.Specifications.Contains(input.specifications))
                .WhereIF(!string.IsNullOrEmpty(input.scanStatus), it => it.ScanStatus.ToString().Contains(input.scanStatus))
                .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.No.Contains(input.keyword) || it.Model.Contains(input.keyword) || it.PrintStatus.ToString().Contains(input.keyword))
                .Where(it => it.DeleteMark == null)
                .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.CreatorTime, OrderByType.Desc)
                .Select(it => new QmsBusiPickListOutput
                {
                    id = it.Id,
                    no = it.No,
                    name = it.Name,
                    model = it.Model,
                    boxNo = it.BoxNo,
                    boxName = it.BoxName,
                    drawingNo = it.DrawingNo,
                    componentName = it.ComponentName,
                    specifications = it.Specifications,
                    unit = it.Unit,
                    qty = it.Qty,
                    remark = it.Remark,
                    syncDate = it.SyncDate,
                    printDate = it.PrintDate,
                    printStatus = SqlFunc.IF(it.PrintStatus.ToString() == "0").Return("未打印").ElseIF(it.PrintStatus.ToString() == "1").Return("已打印").End(""),
                    scanStatus = SqlFunc.IF(it.ScanStatus.ToString() == "0").Return("未扫描").ElseIF(it.ScanStatus.ToString() == "1").Return("已扫描").End(""),
                    scanUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.ScanUserId).Select(p => p.RealName),
                    scanDate = it.ScanDate,
                }).OrderByIF(!string.IsNullOrEmpty(input.sidx), it => input.sidx + " " + input.sort).ToPagedListAsync(input.currentPage, input.pageSize);
            return PageResult<QmsBusiPickListOutput>.SqlSugarPageResult(data);
        }

        /// <summary>
        /// 无分页列表
        /// </summary>
        /// <param name="input">请求参数</param>
        /// <returns></returns>
        private async Task<dynamic> GetNoPageList([FromQuery] QmsBusiPickListQueryInput input)
        {
            var data = await _repository.Context.Queryable<QmsBusiPickEntity>()
                .WhereIF(!string.IsNullOrEmpty(input.no), it => it.No.Contains(input.no))
                .WhereIF(!string.IsNullOrEmpty(input.model), it => it.Model.Contains(input.model))
                .WhereIF(!string.IsNullOrEmpty(input.printStatus), it => it.PrintStatus.ToString().Contains(input.printStatus))
                .WhereIF(!string.IsNullOrEmpty(input.keyword), it => it.No.Contains(input.keyword) || it.Model.Contains(input.keyword) || it.PrintStatus.ToString().Contains(input.keyword))
                .Where(it => it.DeleteMark == null)
                .OrderByIF(string.IsNullOrEmpty(input.sidx), it => it.CreatorTime, OrderByType.Desc)
                .Select(it => new QmsBusiPickListOutput
                {
                    id = it.Id,
                    no = it.No,
                    name = it.Name,
                    model = it.Model,
                    boxNo = it.BoxNo,
                    boxName = it.BoxName,
                    drawingNo = it.DrawingNo,
                    componentName = it.ComponentName,
                    specifications = it.Specifications,
                    unit = it.Unit,
                    qty = it.Qty,
                    remark = it.Remark,
                    syncDate = it.SyncDate,
                    printDate = it.PrintDate,
                    printStatus = SqlFunc.IF(it.PrintStatus.ToString() == "0").Return("未打印").ElseIF(it.PrintStatus.ToString() == "1").Return("已打印").End(""),
                    scanStatus = SqlFunc.IF(it.ScanStatus.ToString() == "0").Return("未扫描").ElseIF(it.ScanStatus.ToString() == "1").Return("已扫描").End(""),
                    scanUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.ScanUserId).Select(p => p.RealName),
                    scanDate = it.ScanDate,
                }).ToListAsync();
            return data;
        }

        /// <summary>
        /// 关闭接口.
        /// </summary>
        /// <param name="ids">ids.</param>
        /// <param name="remark">备注信息.</param>
        /// <returns></returns>
        [HttpPost("CloseFunction")]
        public async Task CloseFunction([FromBody] List<string> ids, string remark)
        {
            //关闭当前数据，关闭需要输入备注，相当于完成已扫描操作
            //查询数据
            var picklist = await _repository.Context.Queryable<QmsBusiPickEntity>().In(it => it.Id, ids).ToListAsync();
            if (picklist.Count > 0)
            {
                try
                {
                    //开启
                    _db.BeginTran();
                    //批量关闭工单
                    var isOk = await _repository.Context.Updateable<QmsBusiPickEntity>().SetColumns(it => new QmsBusiPickEntity()
                    {
                        Remark = remark,
                        ScanStatus = 1,
                        ScanUserId = _userManager.UserId,
                        ScanDate = DateTime.Now,
                    }).Where(it => ids.Contains(it.Id)).ExecuteCommandAsync();
                    //提交
                    _db.CommitTran();
                }
                catch (Exception)
                {
                    //回滚
                    _db.RollbackTran();
                    throw Oops.Oh("关闭失败！");
                }
            }
        }

        /// <summary>
        /// 同步接口.
        /// </summary>
        /// <param name="picklist">集合对象</param>
        /// <returns></returns>
        [HttpPost("Synchronization")]
        public async Task Synchronization(string No)
        {

            if (string.IsNullOrEmpty(No))
                throw Oops.Bah("做番号不能为空!");
            //错误信息统计
            int errorcount = 0;
            //查询数据库中是否有已打印的数据
            //有已打印的数据不能同步，没有已打印的数据进行数据删除
            //插入传过来的装箱单数据
            //var pickcount = await _repository.Context.Queryable<QmsBusiPickEntity>().Where(it => it.PrintStatus == 1 && it.DeleteMark == null && it.EnabledMark == 1).CountAsync();
            //if (pickcount > 0)
            //{
            //    //同步接口失败
            //    throw Oops.Oh("同步接口失败!");
            //}
            //else
            //{
            //删除装箱单数据
            //await _repository.Context.Deleteable<QmsBusiPickEntity>().Where(it => it.PrintStatus == 0).ExecuteCommandAsync();
            //获取数据源[db_datareader]权限[Reservations]用户

            // 如果已经存在，再次同步先逻辑删除再新增 （提示在前端确认）
            var pickAny = await _repository.Context.Queryable<QmsBusiPickEntity>().Where(w => w.No == No && w.DeleteMark == null).AnyAsync();
            if (pickAny)
            {
                await _repository.Context.Updateable<QmsBusiPickEntity>().SetColumns(it => new QmsBusiPickEntity
                {
                    DeleteTime = DateTime.Now,
                    DeleteMark = 1,
                    DeleteUserId = _userManager.UserId
                }).Where(w => w.No == No && w.DeleteMark == null).ExecuteCommandAsync();
            }

            var datalist = await _client.AsTenant().GetConnection("LiLong").SqlQueryable<QmsBusiPickEntity>(@"WITH RecursiveBOMALL AS ( SELECT 做番号, 产品名称,箱号 as '关联箱号',箱图号 as '箱号',名称 as '箱名称',箱图号, 名称,规格,单位,数量, 0 AS Level  
                        FROM [LP_BOMALL_V2]('" + No + @"',10)  WHERE LevelNo<=2 UNION ALL  SELECT e.做番号, e.产品名称,e.箱号,e.箱图号,e.名称, r.箱号,r.箱名称,r.规格,r.单位,r.数量, Level + 1  
                        FROM [LP_BOMALL_V2]('" + No + @"',10) e  INNER JOIN RecursiveBOMALL r ON e.箱图号 = r.关联箱号  )  
                        SELECT 做番号 as 'F_No',产品名称 as 'F_Name',箱号 as 'F_BoxNo',箱名称 as 'F_BoxName',箱图号 as 'F_DrawingNo',名称 as 'F_ComponentName',规格 as 'F_Specifications',
                        单位 as 'F_Unit',数量 as 'F_Qty',GETDATE() as 'F_SyncDate',0 as 'F_PrintStatus',0 as 'F_ScanStatus' FROM RecursiveBOMALL where Level=1").ToListAsync();

            if (datalist.Count == 0)
                throw Oops.Bah("未获取到装箱单实例!");

            var isOk = await _repository.Context.Insertable(datalist).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
            if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1000);

            //}

        }

        /// <summary>
        /// 单选打印条码接口.
        /// </summary>
        /// <param name="id">id.</param>
        /// <param name="sum">数量.</param>
        /// <returns></returns>
        //[HttpPost("PrintSingle")]
        //public async Task<dynamic> PrintSingle(string id, int sum)
        //{
        //    //是否有记录
        //    bool isinsert;
        //    //传入数量(sum)是否与装箱单数量一致
        //    bool issuccess;
        //    //根据传过来的id查询这个装箱单的图号，做番号，产品型号，数量，单位+Guid生成条码规则
        //    var data = await _repository.Context.Queryable<QmsBusiPickEntity>()
        //        .Where(it => it.Id == id)
        //        .Select(it => new QmsBusiPickEntity() { DrawingNo = it.DrawingNo, No = it.No, Model = it.Model, Qty = it.Qty, Unit = it.Unit, Name = it.Name, BoxNo = it.BoxNo, BoxName = it.BoxName, ComponentName = it.ComponentName, Specifications = it.Specifications, Remark = it.Remark, Item = it.Item, SyncDate = it.SyncDate, Barcode = it.Barcode, PrintUserId = it.PrintUserId, PrintDate = it.PrintDate }).ToListAsync();
        //    //生成条码规则
        //    var batch = data[0].DrawingNo + data[0].No + data[0].Model + data[0].Qty + data[0].Unit;
        //    //在打印记录插入一条数据并且把数据返回
        //    //判断该数据在打印记录已经打印，有记录不需要插入数据
        //    var count = await _repository.Context.Queryable<QmsBusiPickRecordEntity>().Where(it => it.PickId == id).CountAsync();
        //    //打印记录插入对象
        //    QmsBusiPickRecordEntity pickrecord = new QmsBusiPickRecordEntity();
        //    //装箱表插入对象
        //    QmsBusiPickEntity pick = new QmsBusiPickEntity();
        //    //打印返回数据
        //    List<ResultDto> result = new List<ResultDto>();
        //    ResultDto resultadd = null;
        //    //没有打印记录并且数量不为0且数量与装箱表数量相等进行数据的插入
        //    issuccess = sum == data[0].Qty;
        //    if (count == 0)
        //    {
        //        if (sum != 0 && issuccess)
        //        {
        //            isinsert = false;
        //            for (int i = 0; i < sum; i++)
        //            {
        //                pickrecord.Id = SnowflakeIdHelper.NextId();
        //                pickrecord.No = data[0].No;
        //                pickrecord.Name = data[0].Name;
        //                pickrecord.Model = data[0].Model;
        //                pickrecord.BoxNo = data[0].BoxNo;
        //                pickrecord.BoxName = data[0].BoxName;
        //                pickrecord.DrawingNo = data[0].DrawingNo;
        //                pickrecord.ComponentName = data[0].ComponentName;
        //                pickrecord.Specifications = data[0].Specifications;
        //                pickrecord.Unit = data[0].Unit;
        //                pickrecord.Qty = data[0].Qty;
        //                pickrecord.Remark = data[0].Remark;
        //                pickrecord.Item = data[0].Item;
        //                pickrecord.SyncDate = data[0].SyncDate;
        //                pickrecord.Barcode = batch + SnowflakeIdHelper.NextId();
        //                pickrecord.PrintUserId = _userManager.UserId;
        //                pickrecord.PrintDate = DateTime.Now;
        //                pickrecord.PickId = id;
        //                resultadd = new ResultDto();
        //                resultadd.DrawingNo = data[0].DrawingNo;
        //                resultadd.ComponentName = data[0].ComponentName;
        //                resultadd.Specifications = data[0].Specifications;
        //                resultadd.Item = data[0].Item;
        //                resultadd.Barcode = pickrecord.Barcode;
        //                //resultadd.Barcode = pickrecord.Barcode;
        //                result.Add(resultadd);
        //                await _repository.Context.Insertable(pickrecord).CallEntityMethod(it => it.Creator()).ExecuteCommandAsync();
        //            }
        //            //更新条码为已打印
        //            await _repository.Context.Updateable<QmsBusiPickEntity>().SetColumns(it => new QmsBusiPickEntity { PrintUserId = _userManager.UserId, PrintDate = DateTime.Now, PrintStatus = 1 }).Where(it => it.Id == id).ExecuteCommandAsync();
        //            return new { result = isinsert, data = result };
        //        }
        //        else
        //        {
        //            isinsert = false;
        //            for (int i = 0; i < sum; i++)
        //            {
        //                pickrecord.Id = SnowflakeIdHelper.NextId();
        //                pickrecord.No = data[0].No;
        //                pickrecord.Name = data[0].Name;
        //                pickrecord.Model = data[0].Model;
        //                pickrecord.BoxNo = data[0].BoxNo;
        //                pickrecord.BoxName = data[0].BoxName;
        //                pickrecord.DrawingNo = data[0].DrawingNo;
        //                pickrecord.ComponentName = data[0].ComponentName;
        //                pickrecord.Specifications = data[0].Specifications;
        //                pickrecord.Unit = data[0].Unit;
        //                pickrecord.Qty = data[0].Qty;
        //                pickrecord.Remark = data[0].Remark;
        //                pickrecord.Item = data[0].Item;
        //                pickrecord.SyncDate = data[0].SyncDate;
        //                pickrecord.Barcode = batch + SnowflakeIdHelper.NextId();
        //                pickrecord.PrintUserId = _userManager.UserId;
        //                pickrecord.PrintDate = DateTime.Now;
        //                pickrecord.PickId = id;
        //                resultadd = new ResultDto();
        //                resultadd.DrawingNo = data[0].DrawingNo;
        //                resultadd.ComponentName = data[0].ComponentName;
        //                resultadd.Specifications = data[0].Specifications;
        //                resultadd.Item = data[0].Item;
        //                resultadd.Barcode = pickrecord.Barcode;
        //                result.Add(resultadd);
        //                await _repository.Context.Insertable(pickrecord).CallEntityMethod(it => it.Creator()).ExecuteCommandAsync();
        //            }
        //            //数量不匹配新增一条数据
        //            pick.Id = SnowflakeIdHelper.NextId();
        //            pick.No = data[0].No;
        //            pick.Name = data[0].Name;
        //            pick.Model = data[0].Model;
        //            pick.BoxNo = data[0].BoxNo;
        //            pick.BoxName = data[0].BoxName;
        //            pick.DrawingNo = data[0].DrawingNo;
        //            pick.ComponentName = data[0].ComponentName;
        //            pick.Specifications = data[0].Specifications;
        //            pick.Unit = data[0].Unit;
        //            pick.Qty = sum;
        //            pick.Remark = data[0].Remark;
        //            pick.SyncDate = data[0].SyncDate;
        //            pick.Barcode = data[0].Barcode;
        //            pick.PrintUserId = data[0].PrintUserId;
        //            pick.PrintDate = data[0].PrintDate;
        //            pick.PrintStatus = 1;
        //            pick.ScanDate = data[0].ScanDate;
        //            await _repository.Context.Insertable(pick).ExecuteCommandAsync();
        //            //更新条码为已打印
        //            await _repository.Context.Updateable<QmsBusiPickEntity>().SetColumns(it => new QmsBusiPickEntity { PrintUserId = _userManager.UserId, PrintDate = DateTime.Now, PrintStatus = 1 }).Where(it => it.Id == id).ExecuteCommandAsync();
        //            return new { result = isinsert, data = result };
        //        }
        //    }
        //    isinsert = true;
        //    return new { result = isinsert };
        //}

        /// <summary>
        /// 多选打印.
        /// </summary>
        /// <param name="ids">ids.</param>
        /// <returns></returns>
        //[HttpPost("PrintMultiple")]
        //public async Task<dynamic> PrintMultiple(List<string> ids)
        //{
        //    //是否成功
        //    bool issuccess = true;
        //    //打印记录插入对象
        //    QmsBusiPickRecordEntity pickrecord = new QmsBusiPickRecordEntity();
        //    //装箱表插入对象
        //    QmsBusiPickEntity pick = new QmsBusiPickEntity();
        //    //打印返回数据
        //    List<ResultDto> result = new List<ResultDto>();
        //    ResultDto resultadd = null;
        //    try
        //    {
        //        _db.BeginTran();
        //        for (int i = 0; i < ids.Count; i++)
        //        {
        //            //查询装箱单是否打印
        //            var data = await _repository.Context.Queryable<QmsBusiPickEntity>().Where(it => it.Id == ids[i]).Select(it => new QmsBusiPickEntity() { DrawingNo = it.DrawingNo, No = it.No, Model = it.Model, Qty = it.Qty, Unit = it.Unit, Name = it.Name, BoxNo = it.BoxNo, BoxName = it.BoxName, ComponentName = it.ComponentName, Specifications = it.Specifications, Remark = it.Remark, Item = it.Item, SyncDate = it.SyncDate, Barcode = it.Barcode, PrintUserId = it.PrintUserId, PrintDate = it.PrintDate, PrintStatus = it.PrintStatus }).ToListAsync();
        //            //生成条码规则
        //            var batch = data[0].DrawingNo + data[0].No + data[0].Model + data[0].Qty + data[0].Unit;
        //            if (data[0].PrintStatus != 1)
        //            {
        //                pickrecord.Id = SnowflakeIdHelper.NextId();
        //                pickrecord.No = data[0].No;
        //                pickrecord.Name = data[0].Name;
        //                pickrecord.Model = data[0].Model;
        //                pickrecord.BoxNo = data[0].BoxNo;
        //                pickrecord.BoxName = data[0].BoxName;
        //                pickrecord.DrawingNo = data[0].DrawingNo;
        //                pickrecord.ComponentName = data[0].ComponentName;
        //                pickrecord.Specifications = data[0].Specifications;
        //                pickrecord.Unit = data[0].Unit;
        //                pickrecord.Qty = data[0].Qty;
        //                pickrecord.Remark = data[0].Remark;
        //                pickrecord.Item = data[0].Item;
        //                pickrecord.SyncDate = data[0].SyncDate;
        //                pickrecord.Barcode = batch + SnowflakeIdHelper.NextId();
        //                pickrecord.PrintUserId = _userManager.UserId;
        //                pickrecord.PrintDate = DateTime.Now;
        //                pickrecord.PickId = ids[i];

        //                resultadd = new ResultDto();
        //                resultadd.DrawingNo = data[0].DrawingNo;
        //                resultadd.ComponentName = data[0].ComponentName;
        //                resultadd.Specifications = data[0].Specifications;
        //                resultadd.Item = data[0].Item;
        //                resultadd.Barcode = pickrecord.Barcode;
        //                result.Add(resultadd);
        //                var insertcount = await _repository.Context.Insertable(pickrecord).CallEntityMethod(it => it.Creator()).ExecuteCommandAsync();
        //                var upddatecount = await _repository.Context.Updateable<QmsBusiPickEntity>().SetColumns(it => new QmsBusiPickEntity { PrintUserId = _userManager.UserId, PrintDate = DateTime.Now, PrintStatus = 1 }).Where(it => it.Id == ids[i]).ExecuteCommandAsync();

        //                if (insertcount > 0 && upddatecount > 0)
        //                {
        //                    issuccess = true;
        //                }
        //                else
        //                {
        //                    issuccess = false;
        //                }
        //            }
        //            continue;
        //        }
        //        if (issuccess)
        //        {
        //            _db.CommitTran();
        //            return new { result = issuccess, data = result };
        //        }
        //        else
        //        {
        //            return new { result = issuccess };
        //            _db.RollbackTran();
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        return Oops.Oh(ex.Message);
        //        _db.RollbackTran();
        //    }
        //}

        /// <summary>
        /// PDF打印
        /// </summary>
        /// <param name="input">打印参数</param>
        /// <param name="exportType">导出类型</param>
        /// <param name="IsSaveLog">是否保存打印记录</param>
        /// <returns></returns>
        [HttpPost("Actions/fastreportPrintSingle")]
        public async Task<dynamic> PrintSingle(ComBasePrintExecuteCrInput input, FastReportExportType exportType = FastReportExportType.PDF, bool IsSaveLog = true)
        {
            //查询打印配置 获取打印模板文件和数据源SQL
            var printConfigData = await _repository.Context.Queryable<ComBasePrintConfigEntity>()
            .LeftJoin<ComBasePrintTemplateEntity>((x, a) => x.PrintTemplateId == a.Id && a.DeleteMark == null)
            .LeftJoin<ComBasePrintDataEntity>((x, a, b) => x.DataSourceId == b.Id && b.DeleteMark == null)
            .Where(x => x.Id == input.printConfigId)
            .Select((x, a, b) => new
            {
                PrintTemplateId = x.PrintTemplateId,
                TemplateFileInfo = a.FileInfo,
                IsCustomer = x.IsCustomer,
                dbLinkId = b.DbLinkId,
                dataSql = b.SqlTemplate,
                labelRuler = x.LabelRulerTemplate
            }).FirstAsync();
            if (printConfigData == null)
                throw Oops.Bah("未查找到相关打印配置!");
            #region 查找打印模板文件路径

            string fileInfoJson = printConfigData.TemplateFileInfo.ToString();
            // 判断是否匹配客户模板
            if (printConfigData.IsCustomer == 1)
            {
                var customerFile = await _repository.Context.Queryable<ComBasePrintTemplateCustomerEntity>()
                    .Where(x => x.CustomerId == input.formCustomerId && x.DeleteMark == null)
                    .Select(s => s.FileInfo).FirstAsync();

                fileInfoJson = customerFile.ToString();
            }

            // 获取模板文件名
            string filename = fileInfoJson.ToList<FileInfoModel>()[0].fileId;
            string filePath = Path.Combine(_fileManager.GetPathByType("annex"), filename);

            #endregion

            //数据源datetable
            //是否有记录
            bool isinsert;
            //传入数量(sum)是否与装箱单数量一致
            bool issuccess;
            //根据传过来的id查询这个装箱单的图号，做番号，产品型号，数量，单位+Guid生成条码规则
            var data = await _repository.Context.Queryable<QmsBusiPickEntity>()
                .Where(it => it.Id == input.formDataId)
                .Select(it => new QmsBusiPickEntity() { DrawingNo = it.DrawingNo, No = it.No, Model = it.Model, Qty = it.Qty, Unit = it.Unit, Name = it.Name, BoxNo = it.BoxNo, BoxName = it.BoxName, ComponentName = it.ComponentName, Specifications = it.Specifications, Remark = it.Remark, Item = it.Item, SyncDate = it.SyncDate, Barcode = it.Barcode, PrintUserId = it.PrintUserId, PrintDate = it.PrintDate }).ToListAsync();
            //生成条码规则
            var batch = data[0].DrawingNo + "*" + data[0].No + "*" + data[0].Model + "*" + data[0].Qty + "*" + data[0].Unit + "*";
            //在打印记录插入一条数据并且把数据返回
            //判断该数据在打印记录已经打印，有记录不需要插入数据
            var count = await _repository.Context.Queryable<QmsBusiPickRecordEntity>().Where(it => it.PickId == input.formDataId).CountAsync();
            //打印记录插入对象
            QmsBusiPickRecordEntity pickrecord = new QmsBusiPickRecordEntity();
            //装箱表插入对象
            QmsBusiPickEntity pick = new QmsBusiPickEntity();
            //打印返回数据
            DataTable primary = await _repository.Context.Queryable<QmsBusiPickEntity>()
                .Where(it => it.Id == input.formDataId)
                .Select(it => new QmsBusiPickEntity() { DrawingNo = it.DrawingNo, ComponentName = it.ComponentName, Specifications = it.Specifications, Item = it.Item, Barcode = it.Barcode, Qty = it.Qty }).ToDataTableAsync();
            primary.Rows.Clear();
            //没有打印记录并且数量不为0且数量与装箱表数量相等进行数据的插入
            issuccess = input.packageQty == data[0].Qty;
            if (count == 0)
            {
                if (input.packageQty != 0 && issuccess)
                {
                    isinsert = false;
                    for (int i = 0; i < input.printQty; i++)
                    {
                        pickrecord.Id = SnowflakeIdHelper.NextId();
                        pickrecord.No = data[0].No;
                        pickrecord.Name = data[0].Name;
                        pickrecord.Model = data[0].Model;
                        pickrecord.BoxNo = data[0].BoxNo;
                        pickrecord.BoxName = data[0].BoxName;
                        pickrecord.DrawingNo = data[0].DrawingNo;
                        pickrecord.ComponentName = data[0].ComponentName;
                        pickrecord.Specifications = data[0].Specifications;
                        pickrecord.Unit = data[0].Unit;
                        pickrecord.Qty = data[0].Qty;
                        pickrecord.Remark = data[0].Remark;
                        pickrecord.Item = data[0].Item;
                        pickrecord.SyncDate = data[0].SyncDate;
                        pickrecord.Barcode = batch + SnowflakeIdHelper.NextId();
                        pickrecord.PrintUserId = _userManager.UserId;
                        pickrecord.PrintDate = DateTime.Now;
                        pickrecord.PickId = input.formDataId;
                        primary.Rows.Add(data[0].DrawingNo, data[0].ComponentName, data[0].Specifications, data[0].Item, pickrecord.Barcode, pickrecord.Qty);
                        await _repository.Context.Insertable(pickrecord).CallEntityMethod(it => it.Creator()).ExecuteCommandAsync();
                    }
                    //更新条码为已打印
                    await _repository.Context.Updateable<QmsBusiPickEntity>().SetColumns(it => new QmsBusiPickEntity { PrintUserId = _userManager.UserId, PrintDate = DateTime.Now, PrintStatus = 1 }).Where(it => it.Id == input.formDataId).ExecuteCommandAsync();
                }
                else
                {
                    isinsert = false;
                    for (int i = 0; i < input.printQty; i++)
                    {
                        pickrecord.Id = SnowflakeIdHelper.NextId();
                        pickrecord.No = data[0].No;
                        pickrecord.Name = data[0].Name;
                        pickrecord.Model = data[0].Model;
                        pickrecord.BoxNo = data[0].BoxNo;
                        pickrecord.BoxName = data[0].BoxName;
                        pickrecord.DrawingNo = data[0].DrawingNo;
                        pickrecord.ComponentName = data[0].ComponentName;
                        pickrecord.Specifications = data[0].Specifications;
                        pickrecord.Unit = data[0].Unit;
                        pickrecord.Qty = data[0].Qty;
                        pickrecord.Remark = data[0].Remark;
                        pickrecord.Item = data[0].Item;
                        pickrecord.SyncDate = data[0].SyncDate;
                        pickrecord.Barcode = batch + SnowflakeIdHelper.NextId();
                        pickrecord.PrintUserId = _userManager.UserId;
                        pickrecord.PrintDate = DateTime.Now;
                        pickrecord.PickId = input.formDataId;
                        primary.Rows.Add(data[0].DrawingNo, data[0].ComponentName, data[0].Specifications, data[0].Item, pickrecord.Barcode);
                        await _repository.Context.Insertable(pickrecord).CallEntityMethod(it => it.Creator()).ExecuteCommandAsync();
                    }
                    //数量不匹配新增一条数据
                    pick.Id = SnowflakeIdHelper.NextId();
                    pick.No = data[0].No;
                    pick.Name = data[0].Name;
                    pick.Model = data[0].Model;
                    pick.BoxNo = data[0].BoxNo;
                    pick.BoxName = data[0].BoxName;
                    pick.DrawingNo = data[0].DrawingNo;
                    pick.ComponentName = data[0].ComponentName;
                    pick.Specifications = data[0].Specifications;
                    pick.Unit = data[0].Unit;
                    pick.Qty = input.packageQty;
                    pick.Remark = data[0].Remark;
                    pick.SyncDate = data[0].SyncDate;
                    pick.Barcode = data[0].Barcode;
                    pick.PrintUserId = data[0].PrintUserId;
                    pick.PrintDate = data[0].PrintDate;
                    pick.PrintStatus = 1;
                    pick.ScanDate = data[0].ScanDate;
                    await _repository.Context.Insertable(pick).ExecuteCommandAsync();
                    //更新条码为已打印
                    await _repository.Context.Updateable<QmsBusiPickEntity>().SetColumns(it => new QmsBusiPickEntity { PrintUserId = _userManager.UserId, PrintDate = DateTime.Now, PrintStatus = 1 }).Where(it => it.Id == input.formDataId).ExecuteCommandAsync();
                }
            }
            else
            {
                throw Oops.Oh("当前装箱单已打印,请勿重复打印!");
            }
            Dictionary<string, DataTable> dicList = new Dictionary<string, DataTable>
            {
                { "PrintData", primary },
            };
            FileResult ms = CreateFR.ExportLabelFastReport(filePath, dicList, exportType);
            return ms;
        }

        /// <summary>
        /// 批量打印.
        /// </summary>
        /// <param name="ids">ids.</param>
        /// <param name="input">input.</param>
        /// <param name="exportType">exportType.</param>
        /// <param name="IsSaveLog">IsSaveLog.</param>
        /// <returns></returns>
        //[HttpPost("Actions/fastreportPrintMultiple")]
        //public async Task<dynamic> PrintMultiple(List<string> ids, ComBasePrintExecuteCrInput input, FastReportExportType exportType = FastReportExportType.PDF, bool IsSaveLog = true)
        //{
        //    //查询打印配置 获取打印模板文件和数据源SQL
        //    var printConfigData = await _repository.Context.Queryable<ComBasePrintConfigEntity>()
        //    .LeftJoin<ComBasePrintTemplateEntity>((x, a) => x.PrintTemplateId == a.Id && a.DeleteMark == null)
        //    .LeftJoin<ComBasePrintDataEntity>((x, a, b) => x.DataSourceId == b.Id && b.DeleteMark == null)
        //    .Where(x => x.Id == input.printConfigId)
        //    .Select((x, a, b) => new
        //    {
        //        PrintTemplateId = x.PrintTemplateId,
        //        TemplateFileInfo = a.FileInfo,
        //        IsCustomer = x.IsCustomer,
        //        dbLinkId = b.DbLinkId,
        //        dataSql = b.SqlTemplate,
        //        labelRuler = x.LabelRulerTemplate
        //    }).FirstAsync();
        //    if (printConfigData == null)
        //        throw Oops.Bah("未查找到相关打印配置!");
        //    #region 查找打印模板文件路径

        //    string fileInfoJson = printConfigData.TemplateFileInfo.ToString();
        //    // 判断是否匹配客户模板
        //    if (printConfigData.IsCustomer == 1)
        //    {
        //        var customerFile = await _repository.Context.Queryable<ComBasePrintTemplateCustomerEntity>()
        //            .Where(x => x.CustomerId == input.formCustomerId && x.DeleteMark == null)
        //            .Select(s => s.FileInfo).FirstAsync();

        //        fileInfoJson = customerFile.ToString();
        //    }

        //    // 获取模板文件名
        //    string filename = fileInfoJson.ToList<FileInfoModel>()[0].fileId;
        //    string filePath = Path.Combine(_fileManager.GetPathByType("annex"), filename);

        //    #endregion
        //    //数据源
        //    //是否成功
        //    bool issuccess = true;
        //    //打印记录插入对象
        //    QmsBusiPickRecordEntity pickrecord = new QmsBusiPickRecordEntity();
        //    //装箱表插入对象
        //    QmsBusiPickEntity pick = new QmsBusiPickEntity();
        //    //打印返回数据
        //    DataTable primary = await _repository.Context.Queryable<QmsBusiPickEntity>()
        //       .Where(it => it.Id == input.formDataId)
        //       .Select(it => new QmsBusiPickEntity() { DrawingNo = it.DrawingNo, ComponentName = it.ComponentName, Specifications = it.Specifications, Item = it.Item, Barcode = it.Barcode }).ToDataTableAsync();
        //    primary.Rows.Clear();
        //    for (int i = 0; i < ids.Count; i++)
        //    {
        //        //查询装箱单是否打印
        //        var data = await _repository.Context.Queryable<QmsBusiPickEntity>().Where(it => it.Id == ids[i]).Select(it => new QmsBusiPickEntity() { DrawingNo = it.DrawingNo, No = it.No, Model = it.Model, Qty = it.Qty, Unit = it.Unit, Name = it.Name, BoxNo = it.BoxNo, BoxName = it.BoxName, ComponentName = it.ComponentName, Specifications = it.Specifications, Remark = it.Remark, Item = it.Item, SyncDate = it.SyncDate, Barcode = it.Barcode, PrintUserId = it.PrintUserId, PrintDate = it.PrintDate, PrintStatus = it.PrintStatus }).ToListAsync();
        //        //生成条码规则
        //        var batch = data[0].DrawingNo + data[0].No + data[0].Model + data[0].Qty + data[0].Unit;
        //        if (data[0].PrintStatus != 1)
        //        {
        //            pickrecord.Id = SnowflakeIdHelper.NextId();
        //            pickrecord.No = data[0].No;
        //            pickrecord.Name = data[0].Name;
        //            pickrecord.Model = data[0].Model;
        //            pickrecord.BoxNo = data[0].BoxNo;
        //            pickrecord.BoxName = data[0].BoxName;
        //            pickrecord.DrawingNo = data[0].DrawingNo;
        //            pickrecord.ComponentName = data[0].ComponentName;
        //            pickrecord.Specifications = data[0].Specifications;
        //            pickrecord.Unit = data[0].Unit;
        //            pickrecord.Qty = data[0].Qty;
        //            pickrecord.Remark = data[0].Remark;
        //            pickrecord.Item = data[0].Item;
        //            pickrecord.SyncDate = data[0].SyncDate;
        //            pickrecord.Barcode = batch + SnowflakeIdHelper.NextId();
        //            pickrecord.PrintUserId = _userManager.UserId;
        //            pickrecord.PrintDate = DateTime.Now;
        //            pickrecord.PickId = ids[i];
        //            primary.Rows.Add(data[0].DrawingNo, data[0].ComponentName, data[0].Specifications, data[0].Item, pickrecord.Barcode);
        //            var insertcount = await _repository.Context.Insertable(pickrecord).CallEntityMethod(it => it.Creator()).ExecuteCommandAsync();
        //            var upddatecount = await _repository.Context.Updateable<QmsBusiPickEntity>().SetColumns(it => new QmsBusiPickEntity { PrintUserId = _userManager.UserId, PrintDate = DateTime.Now, PrintStatus = 1 }).Where(it => it.Id == ids[i]).ExecuteCommandAsync();
        //        }
        //        continue;
        //    }
        //    Dictionary<string, DataTable> dicList = new Dictionary<string, DataTable>
        //    {
        //        { "PrintData", primary },
        //    };

        //    FileResult ms = CreateFR.ExportLabelFastReport(filePath, dicList, exportType);
        //    return ms;
        //}

        /// <summary>
        /// 导出装箱单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("Actions/Export")]
        public async Task<dynamic> Export([FromQuery] QmsBusiPickListQueryInput input)
        {
            var exportData = new List<QmsBusiPickListOutput>();
            if (input.dataType == 0)
                exportData = Clay.Object(await GetList(input)).Solidify<PageResult<QmsBusiPickListOutput>>().list;
            else
                exportData = await GetNoPageList(input);
            List<ParamsModel> paramList = "[{\"value\":\"做番号\",\"field\":\"no\"},{\"value\":\"单位名称\",\"field\":\"name\"},{\"value\":\"产品型号\",\"field\":\"model\"},{\"value\":\"箱号\",\"field\":\"boxNo\"},{\"value\":\"箱名\",\"field\":\"boxName\"},{\"value\":\"图号\",\"field\":\"drawingNo\"},{\"value\":\"部件名称\",\"field\":\"componentName\"},{\"value\":\"规格\",\"field\":\"specifications\"},{\"value\":\"单位\",\"field\":\"unit\"},{\"value\":\"数量\",\"field\":\"qty\"},{\"value\":\"备注\",\"field\":\"remark\"},{\"value\":\"同步日期\",\"field\":\"syncDate\"},{\"value\":\"打印日期\",\"field\":\"printDate\"},{\"value\":\"状态\",\"field\":\"printStatus\"},{\"value\":\"扫描状态\",\"field\":\"scanStatus\"},{\"value\":\"扫描人\",\"field\":\"scanUserId\"},{\"value\":\"扫描日期\",\"field\":\"scanDate\"}]".ToList<ParamsModel>();
            ExcelConfig excelconfig = new ExcelConfig();
            excelconfig.FileName = "装箱单信息.xls";
            excelconfig.HeadFont = "微软雅黑";
            excelconfig.HeadPoint = 10;
            excelconfig.IsAllSizeColumn = true;
            excelconfig.ColumnModel = new List<ExcelColumnModel>();
            foreach (var item in input.selectKey.Split(',').ToList())
            {
                var isExist = paramList.Find(p => p.field == item);
                if (isExist != null)
                    excelconfig.ColumnModel.Add(new ExcelColumnModel() { Column = isExist.field, ExcelColumn = isExist.value, Width = 25 });
            }

            var addPath = FileVariable.TemporaryFilePath + excelconfig.FileName;
            ExcelExportHelper<QmsBusiPickListOutput>.Export(exportData, excelconfig, addPath);
            var fileName = _userManager.UserId + "|" + addPath + "|xls";
            return new
            {
                name = excelconfig.FileName,
                url = "/api/File/Download?encryption=" + DESCEncryption.Encrypt(fileName, "SHZY")
            };
        }

        /// <summary>
        /// 预览.
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("Actions/fastreportGetPreview")]
        public async Task<dynamic> GetPreview([FromBody] ComBasePrintExecuteCrInput input, FastReportExportType exportType = FastReportExportType.Image)
        {
            if (input.printQty.IsNullOrEmpty() || input.printQty <= 0)
                throw Oops.Bah("打印数量不能小于1");
            //input.printQty = 1;  // 预览默认打印数量为1
            //查询打印配置 获取打印模板文件和数据源SQL
            var printConfigData = await _repository.Context.Queryable<ComBasePrintConfigEntity>()
            .LeftJoin<ComBasePrintTemplateEntity>((x, a) => x.PrintTemplateId == a.Id && a.DeleteMark == null)
            .LeftJoin<ComBasePrintDataEntity>((x, a, b) => x.DataSourceId == b.Id && b.DeleteMark == null)
            .Where(x => x.Id == input.printConfigId)
            .Select((x, a, b) => new
            {
                PrintTemplateId = x.PrintTemplateId,
                TemplateFileInfo = a.FileInfo,
                IsCustomer = x.IsCustomer,
                dbLinkId = b.DbLinkId,
                dataSql = b.SqlTemplate,
                labelRuler = x.LabelRulerTemplate
            }).FirstAsync();
            if (printConfigData == null)
                throw Oops.Bah("未查找到相关打印配置!");
            #region 查找打印模板文件路径

            string fileInfoJson = printConfigData.TemplateFileInfo.ToString();
            // 判断是否匹配客户模板
            if (printConfigData.IsCustomer == 1)
            {
                var customerFile = await _repository.Context.Queryable<ComBasePrintTemplateCustomerEntity>()
                    .Where(x => x.CustomerId == input.formCustomerId && x.DeleteMark == null)
                    .Select(s => s.FileInfo).FirstAsync();

                fileInfoJson = customerFile.ToString();
            }

            // 获取模板文件名
            string filename = fileInfoJson.ToList<FileInfoModel>()[0].fileId;
            string filePath = Path.Combine(_fileManager.GetPathByType("annex"), filename);

            #endregion

            //数据源datetable
            //根据传过来的id查询这个装箱单的图号，做番号，产品型号，数量，单位+Guid生成条码规则
            var data = await _repository.Context.Queryable<QmsBusiPickEntity>()
                .Where(it => it.Id == input.formDataId)
                .Select(it => new QmsBusiPickEntity() { DrawingNo = it.DrawingNo, No = it.No, Model = it.Model, Qty = it.Qty, Unit = it.Unit, Name = it.Name, BoxNo = it.BoxNo, BoxName = it.BoxName, ComponentName = it.ComponentName, Specifications = it.Specifications, Remark = it.Remark, Item = it.Item, SyncDate = it.SyncDate, Barcode = it.Barcode, PrintUserId = it.PrintUserId, PrintDate = it.PrintDate }).ToListAsync();
            //生成条码规则
            var batch = data[0].DrawingNo + "*" + data[0].No + "*" + data[0].Model + "*" + data[0].Qty + "*" + data[0].Unit + "*";
            DataTable primary = await _repository.Context.Queryable<QmsBusiPickEntity>()
                .Where(it => it.Id == input.formDataId)
                .Select(it => new QmsBusiPickEntity() { DrawingNo = it.DrawingNo, ComponentName = it.ComponentName, Specifications = it.Specifications, Item = it.Item, Barcode = it.Barcode, Qty = it.Qty }).ToDataTableAsync();
            primary.Rows.Clear();
            for (int i = 0; i < input.printQty; i++)
            {
                primary.Rows.Add(data[0].DrawingNo, data[0].ComponentName, data[0].Specifications, data[0].Item, batch + SnowflakeIdHelper.NextId(), data[0].Qty);
            }
            Dictionary<string, DataTable> dicList = new Dictionary<string, DataTable>
            {
                { "PrintData", primary },
            };
            FileResult ms = CreateFR.ExportLabelFastReport(filePath, dicList, exportType);
            return ms;
        }

        /// <summary>
        /// ZPL单个打印.
        /// </summary>
        /// <param name="Unpack">Unpack</param>
        /// <param name="exportType">exportType</param>
        /// <returns></returns>
        [HttpPost("Actions/fastreportPrintUnpackingExeport")]
        public async Task<FileResult?> PrintUnpackingExeport([FromBody] ComBasePrintExecuteCrInput input, FastReportExportType exportType = FastReportExportType.ZPL)
        {
            //if (!string.IsNullOrEmpty(Unpack.printerIp))
            //{
            //var config = await _repository.Context.Queryable<ComBasePrinterConfigEntity>().Where(x => x.ComputerIp.Contains(Unpack.printerIp) && x.DeleteMark == null && x.EnabledMark == 1).FirstAsync();
            //if (config == null)
            //{
            //    throw Oops.Oh("未找到对应IP地址");
            //}

            //ComBasePrintExecuteCrInput input = new ComBasePrintExecuteCrInput();

            ////查询装箱打印配置
            //var baseEvent = await _repository.Context.Queryable<ComBaseEventEntity>().Where(x => x.EventCode == Unpack.eventCode).OrderBy(x => x.CreatorTime, OrderByType.Desc).FirstAsync();
            //if (baseEvent != null)
            //{
            //    input.printConfigId = baseEvent.PrintConfigId;
            //}
            //input.formDataId = Unpack.formDataId;
            //input.formCustomerId = Unpack.formCustomerId;
            //input.printQty = Unpack.printQty;
            //input.packageQty = Unpack.packageQty;
            //input.formQty = Unpack.formQty;
            //input.printerIp = config.PrinterIp;
            //查询打印配置 获取打印模板文件和数据源SQL
            var printConfigData = await _repository.Context.Queryable<ComBasePrintConfigEntity>()
            .LeftJoin<ComBasePrintTemplateEntity>((x, a) => x.PrintTemplateId == a.Id && a.DeleteMark == null)
            .LeftJoin<ComBasePrintDataEntity>((x, a, b) => x.DataSourceId == b.Id && b.DeleteMark == null)
            .Where(x => x.Id == input.printConfigId)
            .Select((x, a, b) => new
            {
                PrintTemplateId = x.PrintTemplateId,
                TemplateFileInfo = a.FileInfo,
                IsCustomer = x.IsCustomer,
                dbLinkId = b.DbLinkId,
                dataSql = b.SqlTemplate,
                labelRuler = x.LabelRulerTemplate
            }).FirstAsync();
            if (printConfigData == null)
                throw Oops.Bah("未查找到相关打印配置!");
            #region 查找打印模板文件路径

            string fileInfoJson = printConfigData.TemplateFileInfo.ToString();
            // 判断是否匹配客户模板
            if (printConfigData.IsCustomer == 1)
            {
                var customerFile = await _repository.Context.Queryable<ComBasePrintTemplateCustomerEntity>()
                    .Where(x => x.CustomerId == input.formCustomerId && x.DeleteMark == null)
                    .Select(s => s.FileInfo).FirstAsync();

                fileInfoJson = customerFile.ToString();
            }

            // 获取模板文件名
            string filename = fileInfoJson.ToList<FileInfoModel>()[0].fileId;
            string filePath = Path.Combine(_fileManager.GetPathByType("annex"), filename);

            #endregion

            //数据源datetable
            //是否有记录
            bool isinsert;
            //传入数量(sum)是否与装箱单数量一致
            bool issuccess;
            //根据传过来的id查询这个装箱单的图号，做番号，产品型号，数量，单位+Guid生成条码规则
            var data = await _repository.Context.Queryable<QmsBusiPickEntity>()
                .Where(it => it.Id == input.formDataId)
                .Select(it => new QmsBusiPickEntity() { DrawingNo = it.DrawingNo, No = it.No, Model = it.Model, Qty = it.Qty, Unit = it.Unit, Name = it.Name, BoxNo = it.BoxNo, BoxName = it.BoxName, ComponentName = it.ComponentName, Specifications = it.Specifications, Remark = it.Remark, Item = it.Item, SyncDate = it.SyncDate, Barcode = it.Barcode, PrintUserId = it.PrintUserId, PrintDate = it.PrintDate }).ToListAsync();
            //生成条码规则
            var batch = data[0].DrawingNo + "*" + data[0].No + "*" + data[0].Model + "*" + data[0].Qty + "*" + data[0].Unit + "*";
            //在打印记录插入一条数据并且把数据返回
            //判断该数据在打印记录已经打印，有记录不需要插入数据
            var count = await _repository.Context.Queryable<QmsBusiPickRecordEntity>().Where(it => it.PickId == input.formDataId).CountAsync();
            //打印记录插入对象
            QmsBusiPickRecordEntity pickrecord = new QmsBusiPickRecordEntity();
            //装箱表插入对象
            QmsBusiPickEntity pick = new QmsBusiPickEntity();
            //打印返回数据
            DataTable primary = await _repository.Context.Queryable<QmsBusiPickEntity>()
                .Where(it => it.Id == input.formDataId)
                .Select(it => new QmsBusiPickEntity() { DrawingNo = it.DrawingNo, ComponentName = it.ComponentName, Specifications = it.Specifications, Item = it.Item, Barcode = it.Barcode, Qty = it.Qty }).ToDataTableAsync();
            primary.Rows.Clear();
            //没有打印记录并且数量不为0且数量与装箱表数量相等进行数据的插入
            issuccess = input.packageQty == data[0].Qty;
            if (count == 0)
            {
                if (input.packageQty != 0 && issuccess)
                {
                    isinsert = false;
                    for (int i = 0; i < input.printQty; i++)
                    {
                        pickrecord.Id = SnowflakeIdHelper.NextId();
                        pickrecord.No = data[0].No;
                        pickrecord.Name = data[0].Name;
                        pickrecord.Model = data[0].Model;
                        pickrecord.BoxNo = data[0].BoxNo;
                        pickrecord.BoxName = data[0].BoxName;
                        pickrecord.DrawingNo = data[0].DrawingNo;
                        pickrecord.ComponentName = data[0].ComponentName;
                        pickrecord.Specifications = data[0].Specifications;
                        pickrecord.Unit = data[0].Unit;
                        pickrecord.Qty = data[0].Qty;
                        pickrecord.Remark = data[0].Remark;
                        pickrecord.Item = data[0].Item;
                        pickrecord.SyncDate = data[0].SyncDate;
                        pickrecord.Barcode = batch + SnowflakeIdHelper.NextId();
                        pickrecord.PrintUserId = _userManager.UserId;
                        pickrecord.PrintDate = DateTime.Now;
                        pickrecord.PickId = input.formDataId;
                        primary.Rows.Add(data[0].DrawingNo, data[0].ComponentName, data[0].Specifications, data[0].Item, pickrecord.Barcode, pickrecord.Qty);
                        await _repository.Context.Insertable(pickrecord).CallEntityMethod(it => it.Creator()).ExecuteCommandAsync();
                    }
                    //更新条码为已打印
                    await _repository.Context.Updateable<QmsBusiPickEntity>().SetColumns(it => new QmsBusiPickEntity { PrintUserId = _userManager.UserId, PrintDate = DateTime.Now, PrintStatus = 1 }).Where(it => it.Id == input.formDataId).ExecuteCommandAsync();
                    //return new { result = isinsert, data = result };
                }
                else
                {
                    isinsert = false;
                    for (int i = 0; i < input.printQty; i++)
                    {
                        pickrecord.Id = SnowflakeIdHelper.NextId();
                        pickrecord.No = data[0].No;
                        pickrecord.Name = data[0].Name;
                        pickrecord.Model = data[0].Model;
                        pickrecord.BoxNo = data[0].BoxNo;
                        pickrecord.BoxName = data[0].BoxName;
                        pickrecord.DrawingNo = data[0].DrawingNo;
                        pickrecord.ComponentName = data[0].ComponentName;
                        pickrecord.Specifications = data[0].Specifications;
                        pickrecord.Unit = data[0].Unit;
                        pickrecord.Qty = data[0].Qty;
                        pickrecord.Remark = data[0].Remark;
                        pickrecord.Item = data[0].Item;
                        pickrecord.SyncDate = data[0].SyncDate;
                        pickrecord.Barcode = batch + SnowflakeIdHelper.NextId();
                        pickrecord.PrintUserId = _userManager.UserId;
                        pickrecord.PrintDate = DateTime.Now;
                        pickrecord.PickId = input.formDataId;
                        primary.Rows.Add(data[0].DrawingNo, data[0].ComponentName, data[0].Specifications, data[0].Item, pickrecord.Barcode);
                        await _repository.Context.Insertable(pickrecord).CallEntityMethod(it => it.Creator()).ExecuteCommandAsync();
                    }
                    //数量不匹配新增一条数据
                    pick.Id = SnowflakeIdHelper.NextId();
                    pick.No = data[0].No;
                    pick.Name = data[0].Name;
                    pick.Model = data[0].Model;
                    pick.BoxNo = data[0].BoxNo;
                    pick.BoxName = data[0].BoxName;
                    pick.DrawingNo = data[0].DrawingNo;
                    pick.ComponentName = data[0].ComponentName;
                    pick.Specifications = data[0].Specifications;
                    pick.Unit = data[0].Unit;
                    pick.Qty = input.packageQty;
                    pick.Remark = data[0].Remark;
                    pick.SyncDate = data[0].SyncDate;
                    pick.Barcode = data[0].Barcode;
                    pick.PrintUserId = data[0].PrintUserId;
                    pick.PrintDate = data[0].PrintDate;
                    pick.PrintStatus = 1;
                    pick.ScanDate = data[0].ScanDate;
                    await _repository.Context.Insertable(pick).ExecuteCommandAsync();
                    //更新条码为已打印
                    await _repository.Context.Updateable<QmsBusiPickEntity>().SetColumns(it => new QmsBusiPickEntity { PrintUserId = _userManager.UserId, PrintDate = DateTime.Now, PrintStatus = 1 }).Where(it => it.Id == input.formDataId).ExecuteCommandAsync();
                }

            }
            else
            {
                throw Oops.Oh("当前装箱单已打印,请勿重复打印!");
            }
            Dictionary<string, DataTable> dicList = new Dictionary<string, DataTable>
            {
                { "PrintData", primary },
            };
            FileResult ms = CreateFR.ExportLabelFastReport(filePath, dicList, exportType);
            //暂时注释，返回文件流
            //if (exportType == FastReportExportType.ZPL)

            //{
            //    FileStreamResult? fileStream = ms as FileStreamResult;
            //    // 异步发送zpl文件流到指定打印机
            //    await Task.Run(() =>
            //    {
            //        PrintZplExample(input.printerIp, fileStream.FileStream);
            //    });
            //    return ms;
            //}
            return ms;
            //FileStreamResult fileStream = ms as FileStreamResult;
            //var data1 = fileStream.FileStream;
            //var data2 = fileStream.FileDownloadName;
            //var data3 = ms.FileDownloadName;
            //return fileStream;
            //}
            //else
            //{
            //    throw Oops.Oh("请选择打印机");
            //}
        }

        /// <summary>
        /// 批量打印.
        /// </summary>
        /// <param name="ids">ids.</param>
        /// <param name="Unpack">参数.</param>
        /// <param name="exportType">打印类型.</param>
        /// <returns></returns>
        [HttpPost("Actions/fastreportPrintMultiple")]
        public async Task<dynamic> PrintMultiple([FromBody] ComBasePrintExecuteCrInput input, FastReportExportType exportType = FastReportExportType.PDF)
        {
            //查询打印配置 获取打印模板文件和数据源SQL
            var printConfigData = await _repository.Context.Queryable<ComBasePrintConfigEntity>()
            .LeftJoin<ComBasePrintTemplateEntity>((x, a) => x.PrintTemplateId == a.Id && a.DeleteMark == null)
            .LeftJoin<ComBasePrintDataEntity>((x, a, b) => x.DataSourceId == b.Id && b.DeleteMark == null)
            .Where(x => x.Id == input.printConfigId)
            .Select((x, a, b) => new
            {
                PrintTemplateId = x.PrintTemplateId,
                TemplateFileInfo = a.FileInfo,
                IsCustomer = x.IsCustomer,
                dbLinkId = b.DbLinkId,
                dataSql = b.SqlTemplate,
                labelRuler = x.LabelRulerTemplate
            }).FirstAsync();
            if (printConfigData == null)
                throw Oops.Bah("未查找到相关打印配置!");
            #region 查找打印模板文件路径

            string fileInfoJson = printConfigData.TemplateFileInfo.ToString();
            // 判断是否匹配客户模板
            if (printConfigData.IsCustomer == 1)
            {
                var customerFile = await _repository.Context.Queryable<ComBasePrintTemplateCustomerEntity>()
                    .Where(x => x.CustomerId == input.formCustomerId && x.DeleteMark == null)
                    .Select(s => s.FileInfo).FirstAsync();

                fileInfoJson = customerFile.ToString();
            }

            // 获取模板文件名
            string filename = fileInfoJson.ToList<FileInfoModel>()[0].fileId;
            string filePath = Path.Combine(_fileManager.GetPathByType("annex"), filename);

            #endregion

            //打印记录插入对象
            QmsBusiPickRecordEntity pickrecord = new QmsBusiPickRecordEntity();
            //装箱表插入对象
            QmsBusiPickEntity pick = new QmsBusiPickEntity();
            //打印返回数据
            DataTable primary = await _repository.Context.Queryable<QmsBusiPickEntity>()
                .Where(it => it.Id == input.formDataId)
                .Select(it => new QmsBusiPickEntity() { DrawingNo = it.DrawingNo, ComponentName = it.ComponentName, Specifications = it.Specifications, Item = it.Item, Barcode = it.Barcode, Qty = it.Qty }).ToDataTableAsync();
            primary.Rows.Clear();
            try
            {
                for (int i = 0; i < input.ids.Count; i++)
                {
                    //查询装箱单是否打印
                    var data = await _repository.Context.Queryable<QmsBusiPickEntity>().Where(it => it.Id == input.ids[i]).Select(it => new QmsBusiPickEntity() { DrawingNo = it.DrawingNo, No = it.No, Model = it.Model, Qty = it.Qty, Unit = it.Unit, Name = it.Name, BoxNo = it.BoxNo, BoxName = it.BoxName, ComponentName = it.ComponentName, Specifications = it.Specifications, Remark = it.Remark, Item = it.Item, SyncDate = it.SyncDate, Barcode = it.Barcode, PrintUserId = it.PrintUserId, PrintDate = it.PrintDate, PrintStatus = it.PrintStatus }).ToListAsync();
                    //生成条码规则
                    var batch = data[0].DrawingNo + "*" + data[0].No + "*" + data[0].Model + "*" + data[0].Qty + "*" + data[0].Unit + "*";
                    if (data[0].PrintStatus != 1)
                    {
                        pickrecord.Id = SnowflakeIdHelper.NextId();
                        pickrecord.No = data[0].No;
                        pickrecord.Name = data[0].Name;
                        pickrecord.Model = data[0].Model;
                        pickrecord.BoxNo = data[0].BoxNo;
                        pickrecord.BoxName = data[0].BoxName;
                        pickrecord.DrawingNo = data[0].DrawingNo;
                        pickrecord.ComponentName = data[0].ComponentName;
                        pickrecord.Specifications = data[0].Specifications;
                        pickrecord.Unit = data[0].Unit;
                        pickrecord.Qty = data[0].Qty;
                        pickrecord.Remark = data[0].Remark;
                        pickrecord.Item = data[0].Item;
                        pickrecord.SyncDate = data[0].SyncDate;
                        pickrecord.Barcode = batch + SnowflakeIdHelper.NextId();
                        pickrecord.PrintUserId = _userManager.UserId;
                        pickrecord.PrintDate = DateTime.Now;
                        pickrecord.PickId = input.ids[i];
                        primary.Rows.Add(data[0].DrawingNo, data[0].ComponentName, data[0].Specifications, data[0].Item, pickrecord.Barcode, pickrecord.Qty);
                        var insertcount = await _repository.Context.Insertable(pickrecord).CallEntityMethod(it => it.Creator()).ExecuteCommandAsync();
                        var upddatecount = await _repository.Context.Updateable<QmsBusiPickEntity>().SetColumns(it => new QmsBusiPickEntity { PrintUserId = _userManager.UserId, PrintDate = DateTime.Now, PrintStatus = 1 }).Where(it => it.Id == input.ids[i]).ExecuteCommandAsync();
                    }
                    continue;
                }
            }
            catch (Exception ex)
            {
                return Oops.Oh(ex.Message);
            }
            Dictionary<string, DataTable> dicList = new Dictionary<string, DataTable>
            {
                { "PrintData", primary },
            };
            FileResult ms = CreateFR.ExportLabelFastReport(filePath, dicList, exportType);
            return ms;
        }

        /// <summary>
        /// 使用TCP发送ZPL指令到打印机.
        /// </summary>
        /// <param name="printerIp"></param>
        /// <param name="fileStream"></param>
        [NonAction]
        public void PrintZplExample(string printerIp, Stream fileStream)
        {
            using (TcpClient client = new TcpClient(printerIp, 9100))
            {
                using (StreamReader sr = new StreamReader(fileStream))
                {
                    using (StreamWriter writer = new StreamWriter(client.GetStream()))
                    {
                        writer.WriteAsync(sr.ReadToEnd());
                        writer.Flush();
                    }
                }
            }
        }

        #region PDA接口

        /// <summary>
        /// 获取已扫描和未扫描数据条数.
        /// </summary>
        /// <returns></returns>
        [HttpPost("GetDataCount")]
        public async Task<dynamic> GetDataCount()
        {
            //获取已扫描的数量
            var scannedCount = await _repository.Context.Queryable<QmsBusiPickEntity>().Where(it => it.ScanStatus == 1 && it.DeleteMark == null).CountAsync();
            //获取未扫描的数量
            var notScannedCount = await _repository.Context.Queryable<QmsBusiPickEntity>().Where(it => it.ScanStatus == 0 && it.DeleteMark == null).CountAsync();
            return new PickUpOutPutInput() { ScannedCount = scannedCount, NotScannedCount = notScannedCount };
        }

        /// <summary>
        /// 根据做番号获取箱号数据 并且获取已扫描和未扫描数据条数.
        /// </summary>
        /// <param name="input">输入参数.</param>
        /// <returns></returns>
        [HttpPost("GetNoCount")]
        public async Task<dynamic> GetNoCount([FromBody] PickUpPageSizeInput input)
        {
            //根据做番号获取箱号数据
            var data = await _repository.Context.Queryable<QmsBusiPickEntity>().Where(it => it.No == input.No && it.DeleteMark == null).Select(it => new QmsBusiPickEntity() { No = it.No, BoxNo = it.BoxNo, ScanStatus = it.ScanStatus }).ToListAsync();
            List<PickUpDto> pickdto = new List<PickUpDto>();
            List<PickUpDto> distinct = new List<PickUpDto>();
            foreach (var item in data)
            {
                //已扫描的箱号条数
                pickdto.Add(new PickUpDto() { BoxNo = item.BoxNo, No = item.No });
            }
            //根据箱号去重
            var distinctlist = pickdto.GroupBy(it => it.BoxNo).Select(it => it.First()).ToList();
            foreach (var item in distinctlist)
            {
                int scannedCount = data.Where(it => it.No == item.No && it.BoxNo == item.BoxNo && it.ScanStatus == 1).Count();
                int notScannedCount = data.Where(it => it.No == item.No && it.BoxNo == item.BoxNo && it.ScanStatus == 0).Count();
                distinct.Add(new PickUpDtos() { BoxNo = item.BoxNo, No = item.No, ScannedCount = scannedCount, NotScannedCount = notScannedCount });
            }
            //分页
            var pickpagesize = distinct.Skip((input.currentPage - 1) * input.pageSize).Take(input.pageSize).ToList();
            return new { data = pickpagesize };
        }

        /// <summary>
        ///做番号箱号获取扫描的所有数据和未扫描的数据
        /// </summary>
        /// <param name="No">做番号</param>
        /// <param name="BoxNo">箱号</param>
        /// <returns></returns>
        [HttpPost("GetBoxNoCount")]
        public async Task<dynamic> GetBoxNoCount([FromBody] PickUpPageSizeInputs input)
        {
            var scannedCount = await _repository.Context.Queryable<QmsBusiPickEntity>().Where(it => it.DeleteMark == null && it.No == input.No && it.BoxNo == input.BoxNo && it.ScanStatus == 1).Select(it => new PickUpOutput() { ComponentName = it.ComponentName, Qty = it.Qty, Unit = it.Unit, Barcode = it.Barcode, No = it.No, Name = it.Name, Model = it.Model, BoxNo = it.BoxNo, BoxName = it.BoxName, DrawingNo = it.DrawingNo, Specifications = it.Specifications, Remark = it.Remark, Item = it.Item, SyncDate = it.SyncDate, PrintUserId = it.PrintUserId, PrintDate = it.PrintDate, PrintStatus = it.PrintStatus, ScanUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.ScanUserId).Select(p => p.RealName) /*it.ScanUserId*/, ScanDate = it.ScanDate, ScanStatus = it.ScanStatus }).ToListAsync();
            var notScannedCount = await _repository.Context.Queryable<QmsBusiPickEntity>().Where(it => it.DeleteMark == null && it.No == input.No && it.BoxNo == input.BoxNo && it.ScanStatus == 0).Select(it => new PickUpOutput() { ComponentName = it.ComponentName, Qty = it.Qty, Unit = it.Unit, Barcode = it.Barcode, No = it.No, Name = it.Name, Model = it.Model, BoxNo = it.BoxNo, BoxName = it.BoxName, DrawingNo = it.DrawingNo, Specifications = it.Specifications, Remark = it.Remark, Item = it.Item, SyncDate = it.SyncDate, PrintUserId = it.PrintUserId, PrintDate = it.PrintDate, PrintStatus = it.PrintStatus, ScanUserId = SqlFunc.Subqueryable<BaseuserEntity>().Where(p => p.Id == it.ScanUserId).Select(p => p.RealName)/*it.ScanUserId*/, ScanDate = it.ScanDate, ScanStatus = it.ScanStatus }).ToListAsync();

            List<PickUpOutput> scannedcount = new List<PickUpOutput>();
            List<PickUpOutput> notScannedcount = new List<PickUpOutput>();
            foreach (var item in scannedCount)
            {
                scannedcount.Add(new PickUpOutput() { ComponentName = item.ComponentName, Qty = item.Qty, Unit = item.Unit, Barcode = item.Barcode, No = item.No, Name = item.Name, Model = item.Model, BoxNo = item.BoxNo, BoxName = item.BoxName, DrawingNo = item.DrawingNo, Specifications = item.Specifications, Remark = item.Remark, Item = item.Item, SyncDate = item.SyncDate, PrintUserId = item.PrintUserId, PrintDate = item.PrintDate, PrintStatus = item.PrintStatus, ScanUserId = item.ScanUserId, ScanDate = item.ScanDate, ScanStatus = item.ScanStatus });
            }

            foreach (var item in notScannedCount)
            {
                notScannedcount.Add(new PickUpOutput() { ComponentName = item.ComponentName, Qty = item.Qty, Unit = item.Unit, Barcode = item.Barcode, No = item.No, Name = item.Name, Model = item.Model, BoxNo = item.BoxNo, BoxName = item.BoxName, DrawingNo = item.DrawingNo, Specifications = item.Specifications, Remark = item.Remark, Item = item.Item, SyncDate = item.SyncDate, PrintUserId = item.PrintUserId, PrintDate = item.PrintDate, PrintStatus = item.PrintStatus, ScanUserId = item.ScanUserId, ScanDate = item.ScanDate, ScanStatus = item.ScanStatus });
            }
            //模糊查询
            var scannedcountwhere = scannedcount.Where(!string.IsNullOrEmpty(input.keyword), it => it.Barcode.Contains(input.keyword));
            var notScannedcountwhere = notScannedCount.Where(!string.IsNullOrEmpty(input.keyword), it => it.Barcode.Contains(input.keyword));
            //分页
            var scannedcountpagesize = scannedcountwhere.Skip((input.currentPage - 1) * input.pageSize).Take(input.pageSize).ToList();
            var notScannedcountpagesize = notScannedcountwhere.Skip((input.currentPage - 1) * input.pageSize).Take(input.pageSize).ToList();
            var scannedUser = _userManager.RealName;
            return new PickUpOutPutList() { ScannedCount = scannedcountpagesize, NotScannedCount = notScannedcountpagesize, ScannedUser = scannedUser };
        }
        /// <summary>
        /// 扫码接口.
        /// </summary>
        /// <param name="No">做番号.</param>
        /// <param name="BoxNo">箱号.</param>
        /// <param name="DrawingNo">图号.</param>
        /// <param name="Qty">数量.</param>
        /// <returns></returns>
        [HttpPost("ScanInterface")]
        public async Task<dynamic> ScanInterface(string No, string BoxNo, string DrawingNo, decimal Qty)
        {
            //根据做番号和箱号获取未扫描目标数据
            var queryable = await _repository.Context.Queryable<QmsBusiPickEntity>().Where(it => it.No == No && it.BoxNo == BoxNo && it.DeleteMark == null).Select(it => new PickUpScanInterfaceOutPut() { Id = it.Id, No = it.No, BoxNo = it.BoxNo, ComponentName = it.ComponentName, Qty = it.Qty, Unit = it.Unit, Barcode = it.Barcode, DrawingNo = it.DrawingNo, ScanStatus = it.ScanStatus, BoxName = it.BoxName, ScanUserId = it.ScanUserId, ScanDate = it.ScanDate }).ToListAsync();
            //根据图号和数量匹配目标数据
            var data = queryable.Where(it => it.DrawingNo == DrawingNo && it.Qty == Qty && it.ScanStatus == 0).FirstOrDefault();
            //已扫描数据匹配
            var data1 = queryable.Where(it => it.DrawingNo == DrawingNo && it.Qty == Qty && it.ScanStatus == 1).FirstOrDefault();
            if (data1 != null)
            {
                //重复扫描插入到qms_busi_scan表
                QmsBusiScanEntity qmsbusiscan = new QmsBusiScanEntity()
                {
                    Id = SnowflakeIdHelper.NextId(),
                    No = No,
                    BoxNo = BoxNo,
                    BoxName = data1.BoxName,
                    Barcode = data1.Barcode,
                    ScanStatus = 0,
                    ScanUserId = data1.ScanUserId,
                    ScanDate = data1.ScanDate,
                    CreatorUserId = _userManager.UserId,
                    CreatorTime = DateTime.Now,
                };
                await _repository.Context.Insertable(qmsbusiscan).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(a => a.Creator()).ExecuteCommandAsync();
                //throw Oops.Oh("当前条码已扫描，请勿重新扫描！");
                return new { data = new { code = 500, msg = "当前条码已扫描，请勿重新扫描！" } };
            }
            else
            {
                if (data != null)
                {
                    //查询打印记录的条码信息更新到装箱单
                    var pickrecord = await _repository.Context.Queryable<QmsBusiPickRecordEntity>().Where(it => it.PickId == data.Id && it.DeleteMark == null).FirstAsync();
                    var isOk = await _repository.Context.Updateable<QmsBusiPickEntity>().SetColumns(it => new QmsBusiPickEntity() { ScanStatus = 1, ScanUserId = _userManager.UserId, ScanDate = DateTime.Now, Barcode = pickrecord.Barcode }).Where(it => it.No == data.No && it.BoxNo == data.BoxNo && it.DrawingNo == data.DrawingNo && it.Qty == data.Qty).ExecuteCommandAsync();
                    if (!(isOk > 0))
                    {
                        //错误扫描插入到qms_busi_scan表
                        QmsBusiScanEntity qmsbusiscan = new QmsBusiScanEntity()
                        {
                            Id = SnowflakeIdHelper.NextId(),
                            No = No,
                            BoxNo = BoxNo,
                            BoxName = data.BoxName,
                            Barcode = data.Barcode,
                            ScanStatus = 1,
                            ScanUserId = data.ScanUserId,
                            ScanDate = data.ScanDate,
                            CreatorUserId = _userManager.UserId,
                            CreatorTime = DateTime.Now,
                        };
                        await _repository.Context.Insertable(qmsbusiscan).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(a => a.Creator()).ExecuteCommandAsync();
                        throw Oops.Oh("扫码失败！");
                    }
                }
                else
                {
                    throw Oops.Oh("未找到目标条码！");
                }
            }
            return string.Empty;
        }
    }

    /// <summary>
    /// Dto.
    /// </summary>
    public class PickUpDto
    {
        /// <summary>
        /// 做番号.
        /// </summary>
        public string No { get; set; }

        /// <summary>
        /// 箱号.
        /// </summary>
        public string BoxNo { get; set; }

    }
    public class PickUpDtos : PickUpDto
    {
        /// <summary>
        /// 已扫码数量.
        /// </summary>
        public int ScannedCount { get; set; }

        /// <summary>
        /// 未扫码数量.
        /// </summary>
        public int NotScannedCount { get; set; }
    }


    public class PickUpOutput
    {
        /// <summary>
        /// 做番号 .
        /// </summary>
        public string No { get; set; }

        /// <summary>
        /// 单位名称.
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// 产品型号.
        /// </summary>
        public string Model { get; set; }

        /// <summary>
        /// 箱号.
        /// </summary>
        public string BoxNo { get; set; }

        /// <summary>
        /// 箱名.
        /// </summary>
        public string BoxName { get; set; }

        /// <summary>
        /// 图号.
        /// </summary>
        public string DrawingNo { get; set; }

        /// <summary>
        /// 部件名称.
        /// </summary>
        public string ComponentName { get; set; }

        /// <summary>
        /// 规格.
        /// </summary>
        public string Specifications { get; set; }

        /// <summary>
        /// 单位.
        /// </summary>
        public string Unit { get; set; }

        /// <summary>
        /// 数量.
        /// </summary>
        public decimal? Qty { get; set; }

        /// <summary>
        /// 备注.
        /// </summary>
        public string Remark { get; set; }

        /// <summary>
        /// 品目.
        /// </summary>
        public string Item { get; set; }

        /// <summary>
        /// 同步日期.
        /// </summary>
        public DateTime? SyncDate { get; set; }

        /// <summary>
        /// 条码.
        /// </summary>
        public string Barcode { get; set; }

        /// <summary>
        /// 打印人.
        /// </summary>
        public string PrintUserId { get; set; }

        /// <summary>
        /// 打印日期.
        /// </summary>
        public DateTime? PrintDate { get; set; }

        /// <summary>
        /// 状态：0未打印 1已打印.
        /// </summary>
        public int? PrintStatus { get; set; }

        /// <summary>
        /// 扫描状态：0未扫码 1已扫描.
        /// </summary>
        public int? ScanStatus { get; set; }

        /// <summary>
        /// 扫描人.
        /// </summary>
        public string ScanUserId { get; set; }

        /// <summary>
        /// 扫描日期.
        /// </summary>
        public DateTime? ScanDate { get; set; }
    }

    public class PickUpOutPutList
    {
        /// <summary>
        /// 已扫描集合.
        /// </summary>
        public List<PickUpOutput> ScannedCount { get; set; }

        /// <summary>
        /// 未扫描集合.
        /// </summary>
        public List<PickUpOutput> NotScannedCount { get; set; }

        /// <summary>
        /// 扫描人.
        /// </summary>
        public string ScannedUser { get; set; }
    }

    public class PickUpOutPutInput
    {
        /// <summary>
        /// 已扫描数量.
        /// </summary>
        public int ScannedCount { get; set; }

        /// <summary>
        /// 未扫描数量.
        /// </summary>
        public int NotScannedCount { get; set; }
    }

    public class PickUpScanInterfaceOutPut
    {
        public string Id { get; set; }
        /// <summary>
        /// 做番号.
        /// </summary>
        public string No { get; set; }

        /// <summary>
        /// 箱号.
        /// </summary>
        public string BoxNo { get; set; }

        /// <summary>
        /// 箱名.
        /// </summary>
        public string BoxName { get; set; }

        /// <summary>
        /// 部件名称.
        /// </summary>
        public string ComponentName { get; set; }

        /// <summary>
        /// 数量.
        /// </summary>
        public decimal? Qty { get; set; }

        /// <summary>
        /// 单位.
        /// </summary>
        public string Unit { get; set; }

        /// <summary>
        /// 条码.
        /// </summary>
        public string Barcode { get; set; }

        public string DrawingNo { get; set; }

        public int? ScanStatus { get; set; }

        /// <summary>
        /// 扫描人.
        /// </summary>

        public string ScanUserId { get; set; }

        /// <summary>
        /// 扫描日期.
        /// </summary>

        public DateTime? ScanDate { get; set; }
    }

    public class PickUpPageSizeInput : PageInputBase
    {
        /// <summary>
        /// 做番号.
        /// </summary>
        public string No { get; set; }

    }

    public class PickUpPageSizeInputs : PickUpPageSizeInput
    {
        /// <summary>
        /// 装箱单.
        /// </summary>
        public string BoxNo { get; set; }
    }
    #endregion
}
